package com.example.qiandao.utils;

import org.hibernate.annotations.Comment;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;

@Component
public class GenerateCode {

    /**
     * 生成指定长度的随机码，包含大写字母和数字。
     *
     * @param length 随机码长度，默认为8位
     * @return 生成的随机码
     */
    public String generateRandomCode(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0");
        }
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    // 提供默认长度为8的重载方法
    public String generateRandomCode() {
        return generateRandomCode(8);
    }

}
